import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'

// 引入仓库
import store from '@/store'
// 封住一个函数，确定是否含有登录的返回地址
function hasUrl(url: any, next: any) {
  // 通过some 进行查找只要存在即为真
  let result = store.getters.getUser.menus_url.some((item:any) => item == url);
  if (result) {
    next()
  } else {
    next('/home')
  }
}
export const indexRoutes = [
  {
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title: '菜单管理'
    },
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl("/menu", next)
    }
  },
  {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    meta: {
      title: '角色管理'
    },
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl("/role", next)
    }
  },
  {
    path: '/user',
    component: () => import('../views/user/user.vue'),
    meta: {
      title: '管理员管理'
    },
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl("/user", next)
    }
  }
]
const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '/home',
        component: () => import('../views/home.vue')
      },
      ...indexRoutes
    ]
  },

  {
    path: '/:pathMath(.*)',
    redirect: '/index'
  }
]

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes
})

// 全局登录拦截
router.beforeEach((to:any,from:any,next:any)=>{
  // 1.如果去的是登录就next
  if(to.path == '/login'){
    next()
    return
  }
  // 2.如果有登录信息就next
  if(store.getters.getUser){
    next()
    return
  }
  // 3.以上逻辑都不符合就直接登录
  next('login')
})

export default router
